/**
 * 全站路由配置
 *
 * 建议:
 * 1. 代码中路由统一使用name属性跳转(不使用path属性)
 */
import { constantRoutes } from "./constantRoutes";
import Vue from "vue";
import Router from "vue-router";
//  import http from "@/utils/httpRequest";
import { isURL } from "@/utils/validate";
import store from "@/store";

import { getRouters } from "@/router/modules";
Vue.use(Router);

import NProgress from "nprogress";
import "nprogress/nprogress.css";
import { NextLoading } from "@/utils/loading";

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require("./import-" + process.env.NODE_ENV);

// 全局路由(无需嵌套上左右整体布局)
const globalRoutes = [
  {
    path: "/404",
    component: _import("common/404"),
    name: "404",
    meta: {
      title: "404未找到",
    },
  },
  {
    path: "/login",
    component: _import("common/login"),
    name: "login",
    meta: {
      title: "登录",
    },
  },
];

// 主入口路由(需嵌套上左右整体布局)
const mainRoutes = {
  path: "/",
  component: _import("main"),
  name: "main",
  redirect: {
    name: "login",
  },
  meta: {
    title: "主入口整体布局",
  },

  beforeEnter(to, from, next) {
    // let token = Vue.cookie.get("token");
    // TODO
    // if (!token || !/\S/.test(token)) {
    //   clearLoginInfo()
    //   next({ name: 'login' })
    // }
    next();
  },
};

const router = new Router({
  mode: "hash",
  scrollBehavior: () => ({
    y: 0,
  }),
  isAddDynamicMenuRoutes: false, // 是否已经添加动态(菜单)路由
  routes: globalRoutes.concat(mainRoutes),
});

router.beforeEach((to, from, next) => {
  /**
   * 未登录则跳转到登录页
   * 未登录跳转到登录页,也可以通过axios的响应拦截器去实现,但是会先在当前页面渲染一下,再跳转到登录页,会有个闪动的现象
   * 这里通过路由守卫的方式,不会在当前页闪现一下,但是需要在每个路由组件添加一个是否需要登录的标识位,如本项目中的requireAuth字段
   */

  // 添加动态(菜单)路由
  // 1. 已经添加 or 全局路由, 直接访问
  // 2. 获取菜单列表, 添加并保存本地存储
  NProgress.configure({ showSpinner: false });
  NProgress.start();
  if (to.name == "login" || from.path === "/login") {
    NextLoading.start();
  }
  if (
    router.options.isAddDynamicMenuRoutes ||
    fnCurrentRouteType(to, globalRoutes) === "global"
  ) {
    next();
  } else {
    if (sessionStorage.token) {
      var menuList = [];
      var btns = [];
      var menuList_ = getRouters || [];

      for (var i = 0; i < menuList_.length; i++) {
        var menu = {
          menuId: i,
          parentId: 0,
          parentName: null,
          name: menuList_[i].meta.title,
          url: "",
          perms: null,
          type: 0,
          icon: "goodsAdmin",
          orderNum: 0,
          open: null,
          sort: 2,
          list: [],
        };

        for (var j = 0; j < menuList_[i].children.length; j++) {
          if (!menuList_[i].children[j].hidden) {
            var children = {
              menuId: i + "_" + j,
              parentId: i,
              parentName: null,
              name: menuList_[i].children[j].meta.title,
              url: menuList_[i].children[j].path,
              perms: null,
              type: 1,
              icon: "goodsAdmin",
              orderNum: 1,
              open: null,
              list: null,
            };
            menu["list"].push(children);
          }
        }

        menuList.push(menu);
      }

      // return
      window.btns_arr = btns;
      if (window.btns_arr_call) {
        window.btns_arr_call(btns);
      }

      fnAddDynamicMenuRoutes(menuList);
      router.options.isAddDynamicMenuRoutes = true;
      sessionStorage.setItem("menuList", JSON.stringify(menuList || "[]"));
      // sessionStorage.setItem('permissions', JSON.stringify(data.permissions || '[]'))

      var fag = false;
      var path_list = [];
      if (to.path == "/operators-index" || to.path == "/") {
        menuList.map((res) => {
          // console.log(res);
          if (res.url == "operators/index") {
            fag = true;
          } else {
            res.list.map((res2) => {
              var url = res2.url.replace(/\//g, "-");
              path_list.push("/" + url);
            });
          }
        });
      } else {
        fag = true;
      }

      if (fag) {
        next({
          ...to,
          replace: true,
        });
      } else {
        next({
          path: path_list[0],
        });
      }
    } else {
      next({
        path: "/login",
      });
      sessionStorage.setItem("menuList", "[]");
      // sessionStorage.setItem('permissions', '[]')
    }
  }
  NextLoading.done();
});

// 路由加载后
router.afterEach(() => {
  NProgress.done();
  NextLoading.done();
});

/**
 * 判断当前路由类型, global: 全局路由, main: 主入口路由
 * @param {*} route 当前路由
 */
function fnCurrentRouteType(route, globalRoutes = []) {
  var temp = [];
  for (var i = 0; i < globalRoutes.length; i++) {
    if (route.path === globalRoutes[i].path) {
      return "global";
    } else if (
      globalRoutes[i].children &&
      globalRoutes[i].children.length >= 1
    ) {
      temp = temp.concat(globalRoutes[i].children);
    }
  }
  return temp.length >= 1 ? fnCurrentRouteType(route, temp) : "main";
}

/**
 * 添加动态(菜单)路由
 * @param {*} menuList 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function fnAddDynamicMenuRoutes(menuList = [], routes = []) {
  var temp = [];
  for (var i = 0; i < menuList.length; i++) {
    if (menuList[i].list && menuList[i].list.length >= 1) {
      temp = temp.concat(menuList[i].list);
    } else if (menuList[i].url && /\S/.test(menuList[i].url)) {
      menuList[i].url = menuList[i].url.replace(/^\//, "");
      var route = {
        path: menuList[i].url.replace(/\//g, "-"),
        component: null,
        name: menuList[i].url.replace(/\//g, "-"),
        meta: {
          menuId: menuList[i].menuId,
          title: menuList[i].name,
          isDynamic: true,
          isTab: true,
          iframeUrl: "",
        },
      };
      // url以http[s]://开头, 通过iframe展示
      if (isURL(menuList[i].url)) {
        route["path"] = `i-${menuList[i].menuId}`;
        route["name"] = `i-${menuList[i].menuId}`;
        route["meta"]["iframeUrl"] = menuList[i].url;
      } else {
        try {
          route["component"] = _import(`modules/${menuList[i].url}`) || null;
        } catch (e) {}
      }
      routes.push(route);
    }
  }
  if (temp.length >= 1) {
    fnAddDynamicMenuRoutes(temp, routes);
  } else {
    mainRoutes.name = "main-dynamic";
    mainRoutes.children = routes;
    router.addRoutes([
      mainRoutes,
      {
        path: "*",
        redirect: {
          name: "404",
        },
      },
    ]);

    sessionStorage.setItem(
      "dynamicMenuRoutes",
      JSON.stringify(mainRoutes.children || "[]")
    );
    // console.log('\n')
    // console.log('%c!<-------------------- 动态(菜单)路由 s -------------------->', 'color:blue')
    // console.log(mainRoutes)
    // console.log('%c!<-------------------- 动态(菜单)路由 e -------------------->', 'color:blue')
  }
}

// 避免重定向
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch((err) => err);
};

export default router;
